package com.example.myapplicationchat;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class ChatActivity extends AppCompatActivity {
    private EditText messageEditText;
    private Button sendButton;
    private LinearLayout chatLayout;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        messageEditText = findViewById(R.id.message_edit_text);
        sendButton = findViewById(R.id.send_button);
        chatLayout = findViewById(R.id.chat_layout);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = messageEditText.getText().toString().trim();

                if(!message.isEmpty()) {
                    addMessageToChatLayout(message, true);
                    messageEditText.setText("");
                }
            }
        });
    }

    private void addMessageToChatLayout(String message, boolean isSentByUser) {
        TextView messageTextView = new TextView(this);
        messageTextView.setText(message);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );

        if(isSentByUser) {
            layoutParams.gravity = Gravity.END;
            messageTextView.setBackgroundResource(R.drawable.ic_launcher_background);
        } else {
            layoutParams.gravity = Gravity.START;
            messageTextView.setBackgroundResource(R.drawable.a);
        }

        messageTextView.setLayoutParams(layoutParams);
        chatLayout.addView(messageTextView);
    }
}
